package cn.edu.zafu.bigdata.lmr;

import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ClockClient {
    public static void main(String[] args) {
        try {
            // 创建客户端的DatagramSocket
            DatagramSocket clientSocket = new DatagramSocket();
            System.out.println("Clock client is running...");

            // 服务器的IP地址和端口号
            InetAddress serverAddress = InetAddress.getByName("192.168.16.74"); // 将"hostname"替换为服务器的IP地址或主机名
            int serverPort = 1234;

            // 要发送给服务器的消息
            String message = "TIME_REQUEST";
            byte[] sendBuffer = message.getBytes();
            DatagramPacket sendPacket = new DatagramPacket(sendBuffer, sendBuffer.length, serverAddress, serverPort);
            clientSocket.send(sendPacket);

            // 接收服务器返回的时间
            byte[] receiveBuffer = new byte[1024];
            DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);
            clientSocket.receive(receivePacket);

            // 将接收到的字节转换为字符串
            String serverTime = new String(receivePacket.getData(), 0, receivePacket.getLength());
            System.out.println("Server time is: " + serverTime);

            // 关闭客户端的DatagramSocket
            clientSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}